package com.sy.simpleegg.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import com.sy.simpleegg.R
import com.sy.simpleegg.bean.SupplementOrderBean
import com.sy.simpleegg.databinding.DialogSupplementBinding
import com.sy.simpleegg.ext.countDown
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.onClick
import com.sy.simpleegg.ext.setDeviceStatus
import com.sy.simpleegg.ext.showToastMsg
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class SupplementDialog(
    private val supplementList: MutableList<SupplementOrderBean>,
    private var listener: SupplementDialogListener,
): DialogFragment() {

    private lateinit var binding: DialogSupplementBinding

    private var timeDownScope: CoroutineScope? = null

    private var handleJob: Job? = null
    private var handling = false
    private var outing = false
    private var outSuccess = false
    private var count = 0

    private var needCoins = 0L
    private var currentRemainCoins = 0L
    private var lastRemainCoins = 0L
    private var currentId = -1L

    override fun onStart() {
        super.onStart()
//        dialog!!.window!!.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        val width = resources.getDimensionPixelSize(R.dimen.dialog_supplement_width)
        val height = resources.getDimensionPixelSize(R.dimen.dialog_supplement_height)
//        val marginBottom = resources.getDimensionPixelSize(R.dimen.dialog_good_detail_margin_bottom)

//        dialog!!.window!!.setLayout(width, height + marginBottom)
        dialog!!.window!!.setLayout(width, height)
        dialog!!.window!!.setGravity(Gravity.CENTER)
        dialog!!.setCanceledOnTouchOutside(false)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        binding = DialogSupplementBinding.inflate(inflater, container, false)
//        setStyle(STYLE_NO_TITLE, R.style.MyDialog)
//        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT))
//        dialog!!.window!!.setGravity(Gravity.BOTTOM)
        dialog!!.window!!.setBackgroundDrawableResource(R.color.transparent)
//        var wlp = dialog!!.window!!.attributes
//        wlp.gravity = Gravity.BOTTOM
//        wlp.width = WindowManager.LayoutParams.MATCH_PARENT
//        wlp.height = WindowManager.LayoutParams.MATCH_PARENT
//        dialog!!.window!!.attributes = wlp

        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        try {
//            binding.tvTitle.text = title
            binding.tvResult.text = getString(R.string.device_outing)
            binding.tvNeedCoin.text = "0"
            binding.tvRemainCoin.text = "0"
//            binding.layoutClose.tvDismiss.text = "${countDownTime}S"

            binding.layoutClose.tvClose.onClick {
//                dismissAllowingStateLoss()
                if (handling){
                    showToastMsg("工作中，请稍后")
                    return@onClick
                }

            }
            binding.btnBack.onClick {
                if (handling){
                    showToastMsg("工作中，请稍后")
                    return@onClick
                }
                listener.back()
                dismissAllowingStateLoss()
            }

            initHandler(supplementList)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("初始化页面异常：${e.message}")
        }
    }

    override fun showNow(manager: FragmentManager, tag: String?) {
        super.showNow(manager, tag)
//        startCountDown(countDownTime)
    }

    override fun show(manager: FragmentManager, tag: String?) {
        super.show(manager, tag)
//        startCountDown(countDownTime)
    }

    override fun show(transaction: FragmentTransaction, tag: String?): Int {
        val result = super.show(transaction, tag)
//        startCountDown(countDownTime)
        return result

    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        listener.dismiss()
    }

    @SuppressLint("SetTextI18n")
    private fun initHandler(supplementOrders: MutableList<SupplementOrderBean>){
        if (supplementOrders.isEmpty()) return
        handleJob?.cancel()

        handleJob = lifecycleScope.launch(Dispatchers.IO) {
            try {
                handling = true

                val interval = 1000L
                val overCount = 20

                run out@{
                    supplementOrders.forEachIndexed { index, supplementOrderBean ->
                        supplementOrderBean.run {
                            val remainCoins = orderCoins.toLong() - realCoins.toLong()
                            if (remainCoins == 0L) {
                                logFile("异常订单补币，未出数量为0，不需要处理")
                                if (index == supplementList.size - 1){
                                    setDeviceStatus(true)
                                    startCountDown(3)
                                }else{
                                    delay(500)
                                }
                                return@forEachIndexed
                            }

                            withContext(Dispatchers.Main){
                                binding.tvOrderCount.text = "${getString(R.string.order_sort)} ${index + 1}/${supplementOrders.size}"
                                binding.tvNeedCoin.text = remainCoins.toString()
                                binding.tvRemainCoin.text = remainCoins.toString()
                                binding.tvResult.text = requireContext().getString(R.string.device_outing)
                            }
                            currentId = id
                            needCoins = remainCoins
                            currentRemainCoins = remainCoins
                            lastRemainCoins = remainCoins

                            count = 0
                            outing = true
                            listener.supplement(time.replace("-", "").replace(":", "").trim(), remainCoins)

                            do {
                                delay(interval)
                                count ++
                                if (lastRemainCoins > currentRemainCoins){
                                    lastRemainCoins = currentRemainCoins
                                    listener.setRealAmount(id, needCoins - lastRemainCoins)
                                }
                            }while (count < overCount && outing)

                            if (outing){
                                //说明超时，未收到控制板回复，停止剩余订单出币
                                logFile("异常订单补币超时，未收到控制板回复，停止剩余订单出币")
                                withContext(Dispatchers.Main){
                                    binding.tvResult.text = requireContext().getString(R.string.out_coins_finish_err)
                                }
                                return@out
                            }

                            withContext(Dispatchers.Main){
                                binding.tvResult.text = if (outSuccess) {
                                    getString(R.string.out_coins_finish)
                                } else {
                                    setDeviceStatus(false)
                                    getString(R.string.out_coins_finish_err)
                                }
                            }
                            if (!outSuccess) {
                                logFile("出货异常，暂停后续订单出币")
                                return@out
                            }
                            if (index == supplementList.size - 1){
                                setDeviceStatus(true)
                                startCountDown(3)
                            }else{
                                //延迟3秒处理下一个订单
                                delay(3000)
                            }
                        }
                    }
                }

                handling = false
            }catch (e: Exception){
                e.printStackTrace()
                logFile("异常订单处理线程异常：${e.message}")
            }
        }
    }

    /**
     * 刷新二维码
     * @param remainCoins 剩余未出数量
     * @param finish 是否出货结束
     * @param success 出货成功
     */
    fun refreshInfo(remainCoins: String, finish: Boolean, success: Boolean){
        try {
            count = 0

            outSuccess = success
            outing = !finish

//            if (finish){
//                outing = false
//                binding.tvResult.text = if (success) {
//                    getString(R.string.out_coins_finish)
//                } else {
//                    setDeviceStatus(false)
//                    getString(R.string.out_coins_finish_err)
//                }
//                if (currentIndex == supplementList.size){
//                    startCountDown(3)
//                }
//            }
            currentRemainCoins = remainCoins.toLong()
            if (currentRemainCoins == 0L) listener.setRealAmount(currentId, needCoins)
            binding.tvRemainCoin.text = remainCoins
        }catch (e: Exception){
            e.printStackTrace()
            logFile("刷新二维码异常：${e.message}")
        }
    }

    @SuppressLint("SetTextI18n")
    private fun startCountDown(timeout: Int){
        timeDownScope?.cancel()

        countDown(
            time = timeout,
            start = {
                timeDownScope = it
                logFile("开始倒计时")
            },
            end = {
                logFile("结束倒计时")
            },
            next = {
                binding.layoutClose.tvDismiss.text = "${it}S"
                if (it == 0){
                    dismissAllowingStateLoss()
                }
            })
    }

    interface SupplementDialogListener{
        fun dismiss()

        fun back()

        fun supplement(orderNumber: String, coins: Long)

        fun setRealAmount(id: Long, realAmount: Long)
    }

    fun dpToPx(context: Context, dp: Int): Int {
        val density = context.resources.displayMetrics.density
        return Math.round(dp * density)
    }
}